import React, { useContext, useState, useEffect, useCallback } from 'react';
import { useHistory } from 'react-router-dom'
import { myContext } from '../../../../reducer'
import { productionPlanTypeEnum } from '../../enum'
import { postSofPdPlanActFindRelease, getSofPdPlanActFindCp, getSofPdPlanActIssue } from '../../api'
import SelectModules from './Components/SelectModules'
import { PlanListAll } from './style'
import { message, PageHeader, Table, Space, Button, Modal } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons';

const { confirm } = Modal;

/**
 * @description: 生产计划
 * @author: xiaoxujs
 * @updata: xiaoxujs（2021-8-17） 添加业务员
 */

const PlanList = () => {
    const history = useHistory()
    const { state } = useContext(myContext)
    const [listData, setListData] = useState([])
    const [total, setTotal] = useState(0)
    const [currentPage, setCurrentPage] = useState(1)
    const [size, setSize] = useState(10)
    const [selectData, setSelectData] = useState({})
    const listFun = useCallback(
        (parames = {
            currentPage: 1,
            size: 10
        }) => {
            parames.executeState = state.productionPlanType
                ; (async () => {
                    const { code, msg, data } = await postSofPdPlanActFindRelease(parames)
                    if (code === '20000') {
                        setListData(data.records)
                        setTotal(data.total)
                        setCurrentPage(parames.currentPage)
                        setSize(parames.size)
                    } else {
                        message.error(msg)
                    }
                })()
        },
        [state.productionPlanType],
    )
    useEffect(() => {
        listFun()
    }, [listFun])
    //分页
    const pagination = {
        //是否可以改变pagesize//
        showSizeChanger: true,
        //是否可以快速跳转到某页
        showQuickJumper: true,
        //展示一共有多少条数据//
        showTotal: () => `共${total}条`,
        //每页条数
        pageSize: size,
        //当前页数
        current: currentPage,
        //数据总数
        total: total,
        //pageSize 变化的回调
        onShowSizeChange: (current, pageSize) => changePageSize(pageSize, current),
        //页码改变的回调，参数是改变后的页码及每页条数
        onChange: (current) => changePage(current),
    }
    //改变每页条数
    const changePageSize = (pageSizeFun, current) => {
        const parames = {
            currentPage: current,
            size: pageSizeFun,
            ...selectData
        }
        listFun(parames);
    }
    //改变页数
    const changePage = (current) => {
        const parames = {
            currentPage: current,
            size,
            ...selectData
        }
        listFun(parames);
    }
    //挂起
    const handleStop = id => {
        confirm({
            title: '您确定要挂起当前计划吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                const parames = {
                    executeState: 1,
                    pdplanId: id
                }
                handleStopStartApi(parames)
            },
        });
    }
    //激活
    const handleStart = id => {
        confirm({
            title: '您确定要激活当前计划吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                const parames = {
                    executeState: 0,
                    pdplanId: id
                }
                handleStopStartApi(parames)
            },
        });
    }
    //挂起激活接口函数
    const handleStopStartApi = (parames) => {
        ; (async () => {
            const { code, msg } = await getSofPdPlanActFindCp(parames)
            if (code === '20000') {
                if(parames.executeState === 0) {
                    message.success('激活成功！')
                }else if(parames.executeState === 1) {
                    message.success('挂起成功！')
                }
                const parames1 = {
                    currentPage,
                    size,
                    ...selectData
                }
                listFun(parames1);
                //待完成
            } else {
                message.error(msg)
            }
        })()
    }

    //添加生产计划
    const handleAddPlan = () => {
        history.push('/addPlan')
    }
    //发布计划
    const handleNext = (id) => {
        confirm({
            title: '确定要发布当前生产计划?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                ; (async () => {
                    const { code, msg } = await getSofPdPlanActIssue({ pdplanId: id })
                    if (code === '20000') {
                        const parames = {
                            currentPage,
                            size,
                            ...selectData
                        }
                        listFun(parames);
                        message.success('计划发布成功！')
                    } else {
                        message.error(msg)
                    }
                })()
            }
        });
    }
        //进入详情
        const handleEnterDetails = (id) => {
            history.push({pathname: '/productionPlan/details', state: {
                pdPlanId: id
            }})
        }
    const columns = [
        {
            title: '客户名称',
            dataIndex: 'clientName',
            render: (text, recode) => <Button type = 'link' onClick = {() => handleEnterDetails(recode.id)}>{text}</Button>

        },
        {
            title: '合同编号',
            dataIndex: 'conNo'
        },
        {
            title: '产品数量',
            dataIndex: 'amount'
        },
        {
            title: '产品',
            dataIndex: 'product'
        },
        {
            title: '剩余天数',
            dataIndex: 'daysRemaining'
        },
        {
            title: '当前状态',
            dataIndex: 'state'
        },
        {
            title: '业务员',
            dataIndex: 'sellName'
        },

        {
            title: '当前执行部门-当前执行任务',
            render: (text, recode) => <Space>
                {
                    recode.actTasks[0] && recode.actTasks.map(item => <span key={item.accDepartmentName}>{item.accDepartmentName}-{item.taskName} </span>)
                }
            </Space>
        },
        {
            title: '押金缴纳状态',
            render: (text,recode) => <span>
                {recode.isArrival ? "已缴纳": "未缴纳"}
            </span>
        },
        {
            title: '操作',
            render: (text, recode) => <Space>
                {state.productionPlanType === 0 ? <Button type='primary' onClick={() => handleStop(recode.id)} >挂起</Button> : null}
                {state.productionPlanType === 1 ? <Button type='primary' onClick={() => handleStart(recode.id)} >激活</Button> : null}
                {state.productionPlanType === 2 && recode.isArrival ? <Button type='primary' onClick={() => handleNext(recode.id)} >发布计划</Button> : null}
            </Space>
        }
    ];
    return <PlanListAll>
        <PageHeader
            className="site-page-header"
            title={productionPlanTypeEnum[state.productionPlanType]}
            extra={[
                <Button key="1" type="primary" onClick={() => handleAddPlan()} >
                    添加生产计划
                </Button>
            ]}
        />
        <SelectModules setSelectData = {setSelectData} listFun = {listFun}/>
        <Table dataSource={listData} columns={columns} pagination={pagination} rowKey='id' />
    </PlanListAll>
}

export default PlanList